<template>
  <div>
    <custom-container ref="customContainerRef" :config="mianConfig"></custom-container>
    <!-- 添加或修改参数配置对话框 -->
    <setForm
      ref="setFormRef"
      v-model:open="open"
      :title="title"
    />
    <!-- 调度日志详细 -->
    <el-dialog
      v-model="openView"
      title="调度日志详细"
      width="800px"
      append-to-body
    >
      <el-form :model="formDetail" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="日志序号：">{{ formDetail.jobLogId }}</el-form-item>
            <el-form-item label="任务名称：">{{ formDetail.jobName }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务分组：">{{ jobGroupFormat(formDetail) }}</el-form-item>
            <el-form-item label="执行时间：">{{ formDetail.createTime }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="调用方法：">{{ formDetail.invokeTarget }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="日志信息：">{{ formDetail.jobMessage }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="执行状态：">
              {{ jobStatusFormat(formDetail) }}
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item v-if="formDetail.status == 1" label="异常信息：">{{ formDetail.exceptionInfo }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div>
          <el-button @click="openView = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, defineAsyncComponent, getCurrentInstance } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute } from 'vue-router'
import { Delete, Download, View } from '@element-plus/icons-vue'
import { ElButton, ElMessageBox, ElMessage } from 'element-plus'
import usedicts, { DictDirection } from '@/store/modules/dicts'
import { listJobLog, delJobLog, cleanJobLog } from '@/api/monitor/log'

const route = useRoute()
// 获取当前jobID
const jobId = route.params && route.params.jobId
const setForm = defineAsyncComponent(() => import('./components/setForm.vue'))
const dicts = usedicts()
const { t } = useI18n()
const
  single = ref(true),
  multiple = ref(true),
  // 查询参数
  queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    jobName: undefined,
    jobGroup: undefined,
    status: undefined,
  }),
  title = ref(''),
  open = ref(false),
  openView = ref(false),
  formDetail = ref({
    jobLogId: undefined,
    jobName: undefined,
    jobGroup: undefined,
    createTime: undefined,
    invokeTarget: undefined,
    jobMessage: undefined,
    status: undefined,
    exceptionInfo: undefined,
  })
let ids = [],
  customContainerRef = ref(null),
  {
    proxy,
  }:{
  proxy:any
} = getCurrentInstance()
const handleQuery = () => {
  customContainerRef.value.getList()
}
// // 列表选择
const handleSelectionChange = (rows: { [key: string]: any }[]) => {
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  ids = rows.map((item) => item.jobLogId)
  single.value = rows.length != 1
  multiple.value = !rows.length
}
/** 详细按钮操作 */
const handleView = (row:{[key:string]:any}) => {
  const data = { pageNum: 1, pageSize: 10, jobLogId: row.jobLogId }
  listJobLog(data).then(res => {
    formDetail.value = res.data[0]
    openView.value = true
  })
}
/** 删除按钮操作 */
const handleDelete = () => {
  ElMessageBox.confirm(`是否确认删除调度日志编号为"${ ids }"的数据项?`).then(() => delJobLog({ jobLogIds: ids })).then((res) => {
    if (res.code === 200) {
      ElMessage.success('删除成功')
      handleQuery()
    } 
  }).catch((err) => {
    if (err === 'cancel') {
      ElMessage.info('取消清空')
    }
  })
}
/** 清空按钮操作 */
function handleClean() {
  ElMessageBox.confirm('是否确认清空所有调度日志数据项?').then(() => cleanJobLog()).then((res) => {
    if (res.code === 200) {
      handleQuery()
      ElMessage.success('清空成功')
    }
  }).catch((err) => {
    if (err === 'cancel') {
      ElMessage.info('取消清空')
    }
  })
}
/** 导出按钮操作 */
const handleExport = () => {
  proxy.$download('/schedule/job/log/export', {
    ...queryParams.value,
  }, `job_log_${ new Date().getTime() }.xlsx`)
}

const jobGroupFormat = (row) => dicts.getDictLabel({ dict: DictDirection.任务分组, value: row.jobGroup })
const jobStatusFormat = (row) => dicts.getDictLabel({ dict: DictDirection.任务状态, value: row.status })
const mianConfig = computed(() => {
  const queryField = 'monitor.log.queryField.'
  const columns = 'monitor.log.columns.'
  const publicKey = 'public.'
  const btns = 'monitor.log.btns.'
  return {
    query: {
      fields: [
        {
          label: t(`${ queryField }jobName`),
          prop: 'jobName',
        },
        {
          label: t(`${ queryField }jobGroup`),
          prop: 'jobGroup',
          type: 'select',
          option: {
            dictInfo: {
              dict: DictDirection.任务组名,
            },
          },
        },
        {
          label: t(`${ queryField }status`),
          prop: 'status',
          type: 'select',
          option: {
            dictInfo: {
              dict: DictDirection.任务状态,
            },
          },
        },
        {
          label: t(`${ queryField }dateRange`),
          prop: 'dateRange',
          type: 'datePicker',
          option: {
            type: 'daterange',
            valueFormat: 'YYYY-MM-DD',
          },
         
        },
      ],
      formOption: {
        labelWidth: '100px',
      },
      queryParams: queryParams.value,
    },
    btns: [
      {
        title: t(`${ btns }delete`),
        icon: Delete,
        type: 'danger',
        disabled: multiple.value,
        onClick: handleDelete,
        directive: [['hasPermi', ['monitor:job:remove']]],
      },
      {
        title: t(`${ btns }clean`),
        icon: Delete,
        type: 'danger',
        onClick: handleClean,
        disabled: multiple.value,
        directive: [['hasPermi', ['monitor:job:remove']]],
      },
      {
        title: t(`${ publicKey }export`),
        icon: Download,
        onClick: handleExport,
        directive: [['hasPermi', ['monitor:job:export']]],
      },
    ],
    table: {
      columns: [
        { type: 'selection', width: '55', align: 'center' },
        {
          label: t(`${ columns }jobLogId`),
          prop: 'jobLogId',
          align: 'center',
        },
        {
          label: t(`${ columns }jobName`),
          prop: 'jobName',
          align: 'center',
        },
        {
          label: t(`${ columns }jobGroup`),
          prop: 'jobGroup',
          align: 'center',
          formatter: (row) => dicts.getDictLabel({ dict: DictDirection.任务分组, value: row.jobGroup }),
        },
        {
          label: t(`${ columns }invokeTarget`),
          prop: 'invokeTarget',
          align: 'center',
        },
        {
          label: t(`${ columns }jobMessage`),
          prop: 'jobMessage',
          align: 'center',
        },
        {
          label: t(`${ columns }status`),
          prop: 'status',
          align: 'center',
          formatter: (row) => dicts.getDictLabel({ dict: DictDirection.任务状态, value: row.status }),
        },
        {
          label: t(`${ columns }createTime`),
          prop: 'createTime',
          align: 'center',
        },
        {
          label: t(`${ columns }operation`),
          prop: 'operation',
          align: 'center',
          showOverflowTooltip: false,
          className: 'custormFixedCol',
          width: '200',
          fixed: 'right',
          render: (h, params) => {
            const buttons = [
         
              {
                title: t(`${ btns }detail`),
                icon: View,
                clickFun: handleView,
                directive: [['hasPermi', ['monitor:job:query']]],
              },
           
            ]
            return buttons.map((el) => h(
              ElButton,
              {
                text: true,
                type: 'primary',
                icon: el.icon,
                onClick: () => {
                  el.clickFun(params.row)
                },
              },
              {
                default: () => el.title,
              },
            ))
          },
        },
      ],
      event: {
        onSelectionChange: (rows) => {
          handleSelectionChange(rows)
        },
      },
    },
    api: listJobLog,
    customKey: `/monitor/log${ jobId }`,
  }
})
</script>